package cn.wolfcode.web.controller;


import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.domain.Notice;
import cn.wolfcode.ssm.service.INoticeService;
import cn.wolfcode.ssm.query.QueryObject;
import cn.wolfcode.ssm.page.JsonPage;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.font.TrueTypeFont;

import java.util.List;

@Controller
@RequestMapping("/notice")
public class NoticeController {

    @Autowired
    private INoticeService noticeService;


//    @RequiresPermissions(value = {"notice:list","公告通知页面"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){

       //  获取当前登陆对象
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();
        // 通过当前登陆对象的id在中间表拿到notie_id数组
        List<Long> Nid = noticeService.selectNid(employee.getId());
        // 共享到页面上
        model.addAttribute("Nid",Nid);

        PageInfo<Notice> pageResult = noticeService.query(qo);
        model.addAttribute("pageResult", pageResult);

        return "notice/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"notice:delete","公告通知删除"},logical = Logical.OR)
    @ResponseBody
    public JsonPage delete(Long id){
        if (id != null) {
            noticeService.delete(id);
        }
        return new JsonPage();
    }


    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"notice:saveOrUpdate","公告通知新增/编辑"},logical = Logical.OR)
    @ResponseBody
    public JsonPage saveOrUpdate(Notice notice){
        if (notice.getId() != null) {
            noticeService.update(notice);
        }else {
            noticeService.save(notice);
        }
        return new JsonPage();
    }


    @RequestMapping("/check")
    public String check(Model model, Long id){
        // 获取当前登陆对象
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipal();

        // 看看当前用户的id是否包含在id数组里面
        List<Long> Eids = noticeService.selectEid(id);
        if (!Eids.contains(employee.getId())) {
            // 不包含就往中间表数组插入数据
            noticeService.SaveNoticeANDEmployee(id, employee.getId());

        }
        // 通过传过来的id ,得到数据.共享到通知页面
        Notice notices = noticeService.get(id);
        model.addAttribute("notices",notices);

        // 跳转到查看页面
        return "notice/show";
    }
}
